package cn.com.headfree.qynj.util;

import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;


public class AesUtil {
	
	private static final Logger LOG = LogManager.getLogger(AesUtil.class);
	
	private static final String CHARSET_NAME = "UTF-8";
	
	private static final String AES_NAME = "AES";
	
	private static final String ALGORITHM = "AES/CBC/PKCS7Padding";
	
	static {
		Security.addProvider(new BouncyCastleProvider());
	}
	
	public static String encrypt(String content,String key) {
		if(StringUtils.isNotBlank(content)&&StringUtils.isNotBlank(key)) {
			byte[] result=null;
			try {
				Cipher cipher=Cipher.getInstance(ALGORITHM);
				SecretKeySpec keySpec=new SecretKeySpec(key.getBytes(CHARSET_NAME),AES_NAME);
				AlgorithmParameterSpec paramSpec=new IvParameterSpec(key.substring(0, 16).getBytes(CHARSET_NAME));
				cipher.init(Cipher.ENCRYPT_MODE, keySpec,paramSpec);
				result=cipher.doFinal(content.getBytes(CHARSET_NAME));
			} catch (Exception e) {
				LOG.error("------------------------参数加密发生异常------------------------");
				LOG.error("加密对象:{}",content);
				LOG.error("加密key:{}",key);
				LOG.error("异常信息:",e);
			}
			return Base64.encodeBase64String(result);
		}
		return "";
	}
}
